﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.FP;
using Coldairarrow.Entity.PB;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_PickUpPlanBusiness : BaseBusiness<PB_PickUpPlan>, IPB_PickUpPlanBusiness, ITransientDependency
    {
        public PB_PickUpPlanBusiness(IDbAccessor db)
            : base(db)
        {
        }

        #region 外部接口

        public async Task<PageResult<PB_PickUpPlan>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_PickUpPlan>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_PickUpPlan, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_PickUpPlan> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_PickUpPlan data)
        {
           
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_PickUpPlan data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }


        /// <summary>
        /// 获取电视机下的计划信息
        /// </summary>
        /// <param name="DeviceId"></param>
        /// <returns></returns>
        public async Task<List<PB_PickUpPlanList>> GetPickUpPlanList(string DeviceId)
        {
            #region 获取工作流环节信息并取出各级部门
            var _workflow = await Db.GetListBySqlAsync<Base_OverFlow>("select * from Base_OverFlow where Id=(select WorkFlow from PB_DeliveryPlan where States=1 limit 1)");
            //各级部门集合
            List<string> deptids = new List<string>();
            if (!_workflow.IsNullOrEmpty())
            {
                JArray jr = JArray.Parse(_workflow[0].Content);
                foreach (var ss in jr) 
                {
                    deptids.Add(((JObject)ss)["ToDept"]["Id"].ToString());
                }
            }
            #endregion

            #region 判断大屏是第几级
            int _index=-1;
            for (int i=0;i< deptids.Count();i++)
            {
                if (deptids[i].Equals(DeviceId))
                {
                    _index=i;
                }
            }
            #endregion
            StringBuilder sql = new StringBuilder();
            String a = "";
            //下面代码更具_index来判断执行哪个sql
            switch (_index) {
                 
                case 0:
                    sql.Append("select  ");
                    sql.Append("PlannedDate  ");
                    sql.Append(",a.Closingdate ");
                    sql.Append(",c.Name ");
                    sql.Append(",d.Buildingnumber ");
                    sql.Append(",b.TrainNumber ");
                    sql.Append(",b.ShipmentQuantity ");
                    sql.Append(",b.ShipmentWight ");
                    sql.Append(",b.ActualQuantity ");
                    sql.Append(",b.ActualWight ");
                    sql.Append(",b.Message ");
                    sql.Append(",b.Id AS aId ");
                    sql.Append(",a.IsRepeat AS IsRepeat ");
                    sql.Append("FROM ");
                    sql.Append("PB_DeliveryPlan AS a ");
                    sql.Append("INNER JOIN PB_DeliveryPlanDetails AS b on a.Id=b.ParentId ");
                    sql.Append("INNER JOIN PB_Project AS c on b.ProjectId=c.Id ");
                    sql.Append("INNER JOIN PB_Buildingnumber AS d on b.BuildingId=d.Id ");
                    sql.Append("LEFT JOIN PB_DesignList AS f on b.ProjectId=f.ProjectId and b.BuildingId=f.BuildingNumberID ");
                    sql.Append("WHERE ");
                    sql.Append("a.States = 1 ");
                    sql.Append("and ");
                    sql.Append(" f.Id is null ");
                    a = "待创建设计清单";
                    break;
                case 1:
                    sql.Append("select  ");
                    sql.Append(" PlannedDate ");
                    sql.Append(",a.Closingdate ");
                    sql.Append(",c.Name ");
                    sql.Append(",d.Buildingnumber ");
                    sql.Append(",b.TrainNumber ");
                    sql.Append(",b.ShipmentQuantity ");
                    sql.Append(",b.ShipmentWight ");
                    sql.Append(",b.ActualQuantity ");
                    sql.Append(",b.ActualWight");
                    sql.Append(",b.Message  ");
                    sql.Append(",b.Id AS aId ");
                    sql.Append(",a.IsRepeat AS IsRepeat ");
                    sql.Append("from ");
                    sql.Append("PB_DeliveryPlan AS a ");
                    sql.Append("INNER JOIN PB_DeliveryPlanDetails AS b on a.Id=b.ParentId  ");
                    sql.Append("INNER JOIN PB_Project AS c on b.ProjectId=c.Id  ");
                    sql.Append("INNER JOIN PB_Buildingnumber AS d on b.BuildingId=d.Id  ");
                    sql.Append("LEFT JOIN (select a.ProjectId,c.Id from PB_DeliveryNotice AS a inner join PB_DeliveryNoticeItem AS b on a.Id = b.ParentId inner join PB_Buildingnumber AS c on a.ProjectId = c.ProjectId  and b.BuildingNo = c.Buildingnumber) f  ");
                    sql.Append("on ");
                    sql.Append("b.ProjectId=f.ProjectId ");
                    sql.Append("and ");
                    sql.Append("b.BuildingId=f.Id  ");
                    sql.Append("LEFT JOIN PB_DesignList AS g on b.ProjectId=g.ProjectId and b.BuildingId=g.BuildingNumberID  ");
                    sql.Append("where ");
                    sql.Append("a.States = 1 ");
                    sql.Append("and  ");
                    sql.Append("f.Id IS NULL ");
                    sql.Append("and ");
                    sql.Append("g.Id  IS NOT NULL  ");
                    sql.Append("and  ");
                    sql.Append("g.ExamineStatus=2 ");
                    a = "待创建发货通知";
                    break;
                case 2:
                    sql.Append("select  ");
                    sql.Append(" PlannedDate ");
                    sql.Append(",a.Closingdate ");
                    sql.Append(",c.Name ");
                    sql.Append(",d.Buildingnumber ");
                    sql.Append(",b.TrainNumber ");
                    sql.Append(",b.ShipmentQuantity ");
                    sql.Append(",b.ShipmentWight ");
                    sql.Append(",b.ActualQuantity ");
                    sql.Append(",b.ActualWight");
                    sql.Append(",b.Message  ");
                    sql.Append(",b.Id AS aId ");
                    sql.Append(",a.IsRepeat AS IsRepeat ");
                    sql.Append("from ");
                    sql.Append("PB_DeliveryPlan AS a ");
                    sql.Append("INNER JOIN PB_DeliveryPlanDetails AS b on a.Id=b.ParentId  ");
                    sql.Append("INNER JOIN PB_Project AS c on b.ProjectId=c.Id  ");
                    sql.Append("INNER JOIN PB_Buildingnumber AS d on b.BuildingId=d.Id  ");
                    sql.Append("LEFT JOIN PB_PickUpMain AS f on b.ProjectId=f.ProjectId  ");
                    sql.Append("and  ");
                    sql.Append("b.BuildingId=f.BuildingNum ");
                    sql.Append("LEFT JOIN (select a.ProjectId,c.Id,a.AuditStatus from PB_DeliveryNotice AS a inner join PB_DeliveryNoticeItem AS b on a.Id = b.ParentId inner join PB_Buildingnumber AS c on a.ProjectId = c.ProjectId and b.BuildingNo = c.Buildingnumber) g  ");
                    sql.Append("on  ");
                    sql.Append("b.ProjectId=g.ProjectId  ");
                    sql.Append("and  ");
                    sql.Append("b.BuildingId=g.Id ");
                    sql.Append("WHERE ");
                    sql.Append("a.States = 1 ");
                    sql.Append("AND  ");
                    sql.Append("f.Id IS NULL  ");
                    sql.Append("AND  ");
                    sql.Append("g.Id IS NOT NULL  ");
                    sql.Append("AND  ");
                    sql.Append("g.AuditStatus = 1 ");
                    a = "待创建备货单";
                    break;
            }

            if (_index==-1) {
                sql.Append("select  ");
                sql.Append("a.PlannedDate ");
                sql.Append(",a.Closingdate ");
                sql.Append(",c.Name ");
                sql.Append(",d.Buildingnumber ");
                sql.Append(",b.TrainNumber ");
                sql.Append(",b.ShipmentQuantity ");
                sql.Append(",b.ShipmentWight ");
                sql.Append(",b.ActualQuantity ");
                sql.Append(",b.ActualWight ");
                sql.Append(",b.Message  ");
                sql.Append(",b.Id AS aId  ");
                sql.Append("from  ");
                sql.Append("PB_DeliveryPlan AS a  ");
                sql.Append("INNER JOIN PB_DeliveryPlanDetails AS b on a.Id=b.ParentId  ");
                sql.Append("INNER JOIN PB_Project AS c on b.ProjectId=c.Id  ");
                sql.Append("INNER JOIN PB_Buildingnumber AS d on b.BuildingId=d.Id  ");
                sql.Append("LEFT JOIN PB_PickUpMain AS f on b.ProjectId=f.ProjectId  ");
                sql.Append("and  ");
                sql.Append("b.BuildingId=f.BuildingNum ");
                sql.Append("where ");
                sql.Append("a.States=9 ");
                sql.Append("AND ");
                sql.Append("f.Id is null ");
                return await Db.GetListBySqlAsync<PB_PickUpPlanList>(sql.ToString());
            }
         
            var lista =await Db.GetListBySqlAsync<PB_PickUpPlanList>(sql.ToString());
            foreach (var item in lista) {


             item.Message=   item.Name + item.Buildingnumber + a + ",计划发货数量" + item.ShipmentQuantity + ",计划发货重量" + item.ShipmentWight + "千克";
            }
            return lista;
        }

        public async Task<PageResult<PB_PickUpPlanDTO>> GetPickUpPlanLists(PageInput<PB_DispatchConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_PickUpPlan, PB_Project,PB_Buildingnumber, Base_Department,PB_Vehicle, PB_PickUpPlanDTO>> select = (a, b, c, d,e) => new PB_PickUpPlanDTO
            {
              ProjectNames=b.Name,
              BuildingnumberNames=c.Buildingnumber,
              DepartmentNames=d.Name,
              Vehicless=e.PlateNO,

            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Buildingnumber>() on a.BuildingnumberId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_Department>() on a.DepartmentId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_Vehicle>() on a.Vehicles equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d,e);

            if (!input.Search.Keyword.IsNullOrEmpty()) {
                q = q.Where(m=>m.ProjectNames.Contains(input.Search.Keyword)||m.BuildingnumberNames.Contains(input.Search.Keyword));
            }
            return await q.GetPageResultAsync(input);
        }

        #endregion

        #region 私有成员

        #endregion
    }
}